package com.arges.controller;

import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author fanweitao
 * @date 2023/04/13
 */
public class Test10 {

    public static void main(String[] args) {

        List<TreeNode> treeNodeList = new ArrayList<>();
        treeNodeList.add(new TreeNode("001", 5, 2));
        treeNodeList.add(new TreeNode("001001", 7, 10));
        treeNodeList.add(new TreeNode("001002", 5, 8));
        treeNodeList.add(new TreeNode("001001001", 3, 5));
        for (int i = 0; i < 10000; i++){
            treeNodeList.add(new TreeNode("001002"+i, 5, 8));
        }
        long startTime = System.currentTimeMillis();
        List<TreeNode> collect = treeNodeList.stream().map(item -> {

            String code = item.getTree();
            String pattern = "^" + code + "(?!$).*";

            Pattern compile = Pattern.compile(pattern);
            AtomicInteger itemValue = new AtomicInteger(item.getValue());
            AtomicInteger itemValue2 = new AtomicInteger(item.getValue2());

            treeNodeList.forEach(treeNode -> {
                Matcher matcher = compile.matcher(treeNode.getTree());
                if (matcher.matches()) {
                    itemValue.addAndGet(treeNode.getValue());
                    itemValue2.addAndGet(treeNode.getValue2());
                }
            });
            return new TreeNode(code, itemValue.intValue(), itemValue2.intValue());
        }).collect(Collectors.toList());

        long endTime = System.currentTimeMillis();
        System.out.println("time: " + (endTime - startTime));

        System.out.println(JSON.toJSONString(collect));
    }

    static class TreeNode {
        private String tree;
        private int value;
        private int value2;

        public TreeNode(String tree, int value, int value2) {
            this.tree = tree;
            this.value = value;
            this.value2 = value2;
        }

        public TreeNode() {
        }


        public String getTree() {
            return tree;
        }

        public int getValue() {
            return value;
        }

        public void setTree(String tree) {
            this.tree = tree;
        }

        public void setValue(int value) {
            this.value = value;
        }

        public int getValue2() {
            return value2;
        }

        public void setValue2(int value2) {
            this.value2 = value2;
        }
    }

}
